<template>
  <VPage class="app-container">
    <div class="relative">
      <CategoryWrap
        type="sku"
        @toggle="toggle"
        @node-click="handleNodeClick"
      ></CategoryWrap>
      <div
        class="rightWrap"
        :style="{ 'margin-left': isShowLeft ? containerWidth + 'px' : '0px' }"
      >
        <VTable ref="tableRef" v-bind="tableOptins">
          <template #form="{ form }">
            <VGroup>
              <el-select class="selectClass !w-[115px]" v-model="form.skuRange.type">
                <el-option
                  v-for="item in skuOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <multi-input
                v-model="form.skuRange.value"
                placeholder="请输入"
                class="w-50"
              ></multi-input>
            </VGroup>
            <multi-input v-model="form.spu" placeholder="SPU" class="w-50"></multi-input>
            <VGroup>
              <el-select class="selectClass !w-[115px]" v-model="form.languageRange.type">
                <el-option
                  v-for="item in languageOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-input
                v-model="form.languageRange.value"
                placeholder="请输入"
                clearable
                class="w-40"
              />
            </VGroup>
            <select-warehouse
              v-model="form.warehouse_id"
              placeholder="仓库"
              style="max-width: 150px"
            ></select-warehouse>
            <template v-if="activeName == 0">
              <el-select
                class="!w-[150px]"
                v-model="form.sales_status"
                placeholder="销售状态"
                multiple
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].salesStatusText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </template>
            <el-select
              class="!w-[150px]"
              v-model="form.purchase_status"
              placeholder="货源状态"
              multiple
            >
              <el-option
                v-for="item in options['goods.GoodsSku']?.[0].supplyStatusText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-select
              class="!w-[150px]"
              v-model="form.is_combination"
              placeholder="是否组合SKU"
            >
              <el-option
                v-for="item in options['goods.GoodsSku']?.[0].mainAttributeText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <VGroup>
              <el-select class="selectClass !w-[115px]" v-model="form.timeRange.type">
                <el-option
                  v-for="item in timeOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-date-picker
                v-model="form.timeRange.value"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="max-width: 300px"
                :default-time="defaultTime()"
              />
            </VGroup>
            <VGroup>
              <el-select class="selectClass !w-[115px]" v-model="form.personRange.type">
                <el-option
                  v-for="item in personOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <select-personnel
                class="w-40"
                v-model="form.personRange.value"
                :multiple="true"
                placeholder="请选择"
              ></select-personnel>
            </VGroup>

            <el-select class="!w-[150px]" v-model="form.field_3" placeholder="是否多属性">
              <el-option
                v-for="item in options['goods.GoodsSku']?.[0].mainAttributeText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
          <template #toolbar_btns>
            <VButton
              auth="/goods/goods-management/spu-list/add"
              type="primary"
              @click="handleDelete"
              >确认删除商品
            </VButton>
            <div class="ml-auto">
              <el-select
                class="!w-[150px]"
                v-model="temple_id"
                placeholder="请选择清退规则"
                clearable
                @change="changeTemple"
              >
                <el-option
                  v-for="item in clearList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
              <el-button type="primary" @click="showRuleList">清退规则列表</el-button>
            </div>
          </template>
        </VTable>
      </div>
    </div>
    <AdvancedSearch
      ref="searchRef"
      :options="options"
      @condition="getConditionList"
      @query="queryForm"
    >
    </AdvancedSearch>
    <VLog ref="roleLog" class="dialogPublic" :api="queryLogList" options="spuId"></VLog>
    <RuleList ref="RuleListRef"></RuleList>
  </VPage>
</template>
<script setup name="Goods-managementSku-list" lang="jsx">
import {
  queryConditionList,
  conditionSave,
  conditionDelete,
  queryLogList,
  skuRecycle,
} from "../api";
import { queryClearList, getClearrulesList } from "./api";
import { getOptions } from "@/api/index.js";
import AdvancedSearch from "../components/AdvancedSearch";
import VLog from "@/components/VLog";
import VImage from "@/components/Image/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { nextTick, ref, reactive } from "vue";
import { useRouter } from "vue-router";
import SelectWarehouse from "@/components/SelectWarehouse";
import CategoryWrap from "@/components/CategoryWrap";
import RuleList from "./components/RuleList";

const tableRef = ref();
const router = useRouter();
// 获取
const fetchOption = () => {
  getOptions({
    name: [
      "goods.GoodsSpu",
      "goods.GoodsSku",
      "goods.GoodsSkuSalesInfo",
      "goods.GoodsSkuSupplier",
      "goods.GoodsSkuAccessories",
      "goods.GoodsSkuSupplier",
      "gallery.GoodsSkuGalleryContents",
    ],
  }).then((res) => {
    options.value = res.data;
  });
};
fetchOption();

const tableOptins = reactive({
  showHeaderOverflow: false,
  showOverflow: false,
  rowConfig: { height: 140 },
  formConfig: {
    save: "clearList",
    data: {
      skuRange: { type: "sku", value: [], range: false },
      spu: "",
      languageRange: { type: "sku_cn_title", value: [], range: true },
      timeRange: { type: "dev_add_time", value: [], range: true },
      personRange: { type: "developer_id", value: [], range: false },
      warehouse_id: null,
      sales_status: "",
      purchase_status: "",
      is_combination: "",
      field_3: "",
      product_attribute: "",
      sample_testing: "",
      purchaseRange: { type: "purchase_price", value: [], range: true },
      weightRange: { type: "packing_weight_g", value: [], range: true },
    },
  },
  columns: [
    { type: "checkbox", width: "40", fixed: "left" },
    {
      field: "name",
      title: "产品",
      width: "390",
      slots: {
        default: ({ row, level }) => {
          return (
            <div class="flex justify-start pr-3">
              <div class="relative" style="width:100px;height:100px">
                {row.brand_type != 1 && (
                  <div
                    class={[
                      "absolute",
                      "text-white",
                      "absolute-radius",
                      "z-10",
                      row.brand_type == 1 ? "bg-red-600" : "bg-gray-600",
                    ]}
                  >
                    {row.brand_type_text}
                  </div>
                )}
                <VImage
                  src={row.attr_img_watermark || row.attr_img}
                  width={100}
                  height={100}
                ></VImage>
              </div>
              <div class="ml-3 flex-1">
                <div class="w-full flex justify-start">
                  <div
                    class="truncate flex-1 w-24 text-[16px] base-text-color cursor-pointer"
                    onClick={() => handleView(row.spu_id)}
                  >
                    SKU:{row.sku}
                  </div>
                </div>
                <div class="w-full mr-2">{`自定义SKU：${row.custom_sku}`}</div>
                <div>
                  <span class="truncate">SPU状态：{row.spu_status_text}</span>
                </div>
                <div class="flex justify-start mb-1">{row.spu_category_text}</div>

                <div class="flex justify-start">
                  {row.purchase_days && row.purchase_days > 0 ? (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="采购天数"
                      placement="top"
                    >
                      <div class="btn-style">{row.purchase_days} 天</div>
                    </el-tooltip>
                  ) : (
                    ""
                  )}
                  {row.min_order ? (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="起批量"
                      placement="top"
                    >
                      <div class="btn-style">{row.min_order} 件起批</div>
                    </el-tooltip>
                  ) : (
                    ""
                  )}
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content={row.is_combination_text}
                    placement="top"
                  >
                    <div class="btn-style">{row.is_combination_text} </div>
                  </el-tooltip>
                </div>
              </div>
            </div>
          );
        },
      },
    },
    {
      field: "product-name",
      title: "产品名称",
      width: "200",
      slots: {
        default: ({ row, level }) => {
          return (
            <div class="">
              <el-tooltip
                className="item"
                effect="dark"
                content={row.sku_cn_title}
                placement="top"
              >
                <div class="overflow-line2">{row.sku_cn_title}</div>
              </el-tooltip>
              <el-tooltip
                className="item"
                effect="dark"
                content={row.sku_en_title}
                placement="top"
              >
                <div class="overflow-line2">{row.sku_en_title}</div>
              </el-tooltip>
            </div>
          );
        },
      },
    },
    {
      field: "product-type",
      title: "产品类型/采购信息",
      width: "200",
      slots: {
        default: ({ row, level }) => {
          return (
            <div>
              {row.sample_testing == 0 ? (
                <div class="">未检测</div>
              ) : row.sample_testing == 1 ? (
                <div class="flex items-center">
                  <svg-icon icon-class="state_finish_cover1" class="text-green-400" />{" "}
                  样品检测通过
                </div>
              ) : row.sample_testing == 2 ? (
                <div class="flex items-center">
                  {" "}
                  <svg-icon icon-class="hint_cover1" class="text-red-400" />
                  样品检测异常
                </div>
              ) : (
                ""
              )}
              <div class="text-xs">
                采购价:¥{row.purchase_price}(最近¥{row.latest_purchase_price}/最低¥0/平均¥
                {row.average_purchase_price})
              </div>
            </div>
          );
        },
      },
    },
    {
      field: "product-info",
      title: "产品信息",
      width: "200",
      slots: {
        default: ({ row, level }) => {
          return (
            <div>
              <div class="mb-1 ">
                毛重{row.gross_weight_g}g<span>｜</span>净重
                {row.net_weight_g}g<span>｜</span>包裹重
                {row.packing_weight_g}g
              </div>
              <div class="mb-1 text-xs">
                产品尺寸 {row.product_size_cm?.length || "0.00"}*
                {row.product_size_cm?.width || "0.00"}*
                {row.product_size_cm?.height || "0.00"}cm
              </div>
              <div class="text-xs">
                包装尺寸{row.packing_size_cm?.length}*{row.packing_size_cm?.width}*
                {row.packing_size_cm?.height}cm
              </div>
            </div>
          );
        },
      },
    },
    {
      field: "sales",
      title: "近30天销量",
      width: "120",
      sortable: true,
      slots: {
        default: ({ row }) => {
          return (
            <div className="flex items-center base-text-color">
              <div>{row.sales || 0}</div>
              <svg-icon icon-class="tongji" />
            </div>
          );
        },
      },
    },
    {
      field: "stock",
      title: "库存",
      width: "200",
      slots: {
        default: ({ row }) => {
          return (
            <div class="flex items-center base-text-color">
              <div>{row.inventory}</div>
              <svg-icon icon-class="tongji" />
            </div>
          );
        },
      },
    },
    {
      field: "account_type_text",
      title: "销售毛利率",
      width: "120",
      slots: {
        default: ({ row }) => {
          return (
            <div class="flex items-center base-text-color">
              <div>0</div>
              <svg-icon icon-class="tongji" />
            </div>
          );
        },
      },
    },
    {
      field: "operator",
      title: "操作人员",
      width: "200",
      slots: {
        default: ({ row }) => {
          return (
            <div className="w-full column-operator-time text-[var(--base-text-color)]">
              <div class="text-xs pt-1 leading-5">
                <span class="text-[var(--base-sub-text-color)]">添加: </span>
                {row.create_user_text}
              </div>
              <div class="text-xs pt-1 leading-5">
                <span class="text-[var(--base-sub-text-color)]">开发: </span>
                {row.developer_text}
              </div>
              <div class="text-xs pt-1 leading-5">
                <span class="text-[var(--base-sub-text-color)]">审核: </span>
                {row.dev_reviewer_text}
              </div>
              <div class="text-xs pt-1 leading-5">
                <span class="text-[var(--base-sub-text-color)]">品质: </span>
                {row.quality_inspector_text}
              </div>
              <div class="text-xs pt-1 leading-5">
                <span class="text-[var(--base-sub-text-color)]">采购: </span>
              </div>
              <div class="text-xs pt-1 leading-5">
                <span class="text-[var(--base-sub-text-color)]">图片: </span>
                {row.img_processor_text}
              </div>
              <div class="text-xs pt-1 leading-5">
                <span class="text-[var(--base-sub-text-color)]">编辑: </span>
                {row.editor_text}
              </div>
            </div>
          );
        },
      },
    },
    {
      field: "operator-time",
      title: "操作时间",
      width: "420",
      slots: {
        default: ({ row }) => {
          return (
            <div className="w-full column-operator-time flex justify-start text-[#333333]">
              <div className="lef w-3/6">
                <div class="text-xs pt-1 leading-5">
                  <span class="text-[var(--base-sub-text-color)]">开发添加: </span>
                  {row.dev_add_time}
                </div>
                <div className="text-xs pt-1 leading-5">
                  <span class="text-[var(--base-sub-text-color)]">检测通过:</span>
                </div>
                <div class="text-xs pt-1 leading-5">
                  <span class="text-[var(--base-sub-text-color)]">开发审核: </span>
                  {row.dev_review_time}
                </div>
                <div class="text-xs pt-1 leading-5">
                  <span class="text-[var(--base-sub-text-color)]">拿样时间: </span>
                  {row.sample_detection_time}
                </div>
              </div>
              <div>
                <div class="text-xs pt-1 leading-5">
                  <span class="text-[var(--base-sub-text-color)]">图片任务: </span>
                  {row.image_processing_time}
                </div>
                <div class="text-xs pt-1 leading-5">
                  <span class="text-[var(--base-sub-text-color)]">图片审核: </span>
                </div>
                <div class="text-xs pt-1 leading-5">
                  <span class="text-[var(--base-sub-text-color)]">刊登上架: </span>
                </div>
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "操作",
      width: "76",
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return (
            <div class="table-option">
              <div>
                <el-button type="primary" link onClick={() => viewLog(row.spu_id)}>
                  {" "}
                  日志
                </el-button>
              </div>
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    seq: true,
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: async ({ page, form }) => {
        const res = await queryClearList({ ...form, ...page });
        return new Promise(function (resolve) {
          resolve({
            data: res.data,
            total: res.total,
          });
        });
      },
    },
  },
});
//更新表格数据
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};

// form option
const skuOption = [
  { label: "系统SKU", value: "sku" },
  { label: "自定义SKU", value: "custom_sku" },
  { label: "赛盒SKU", value: "sai_he_sku" },
];
const languageOption = [
  { label: "中文名称", value: "sku_cn_title" },
  { label: "英文名称", value: "sku_en_title" },
];
const timeOption = [
  { label: "开发添加", value: "dev_add_time" },
  { label: "开发审核", value: "dev_review_time" },
  { label: "拿样时间", value: "sample_detection_time" },
  { label: "检测时间", value: "test_detection_time" },
  { label: "图片任务", value: "image_processing_time" },
  { label: "图片审核", value: "iamge_audit_time" },
  { label: "刊登上架", value: "publish_detection_time" },
];
const personOption = [
  { label: "开发人员", value: "developer_id" },
  { label: "添加人员", value: "create_user" },
  { label: "审核人员", value: "dev_reviewer_id" },
  { label: "品质人员", value: "quality_inspector_id" },
  { label: "采购人员", value: "purchaser_id" },
  { label: "图片人员", value: "img_processor_id" },
  { label: "编辑人员", value: "img_processor_id" },
];

const data = reactive({
  menuList: [],
  fieldOptions: null,
  rowId: null,
  options: {},
  activeName: 0,
  searchOptions: [],
  searchId: null,
  searchName: "",
  isShowLeft: true,
  clearList: [],
  temple_id: "",
  containerWidth: 280,
});
const {
  options,
  activeName,
  searchOptions,
  searchName,
  isShowLeft,
  clearList,
  temple_id,
  containerWidth,
} = toRefs(data);

//选中菜单树
const handleNodeClick = (data) => {
  nextTick(() => {
    tableRef?.value.setFormField("spu_category", data.child_ids || data.id);
    refresh();
  });
};

//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords();
};

// 查询条件列表
const getConditionList = async () => {
  try {
    const res = await queryConditionList({
      apiName: "clearList",
    });
    searchOptions.value = res.data;
  } catch (e) {
    throw Error(e);
  }
};
getConditionList();

// 高级搜索
const searchRef = ref();
const openSearch = () => {
  const form = tableRef.value.getForm();
  nextTick(() => {
    searchRef.value.open(form);
  });
};

const queryForm = (data = {}) => {
  const form = tableRef.value.getForm();
  tableRef.value.setForm({ ...form, ...data });
  nextTick(() => {
    tableRef.value.query();
  });
};

// 查看
const handleView = (spuId) => {
  window.$globalUtils.routerPlugin.push({
    path: "/task/product/detail",
    query: {
      spuId,
    },
  });
};

//查看日志
const roleLog = ref();
const viewLog = (id) => {
  roleLog.value.open(id);
};

const changeTemple = (val) => {
  tableRef.value.setForm({ temple_id: val });
  nextTick(() => {
    tableRef.value.query();
  });
};

const RuleListRef = ref();
const showRuleList = () => {
  RuleListRef.value.open();
};

const handleDelete = async () => {
  const records = getSelectRow().map((i) => i.id);
  if (records.length == 0) {
    ElMessage({
      showClose: true,
      message: "请选择一条数据！",
      type: "error",
    });
    return false;
  }
  ElMessageBox.confirm("是否删除商品?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "error",
    confirmButtonClass: "btnFalses",
  }).then(async () => {
    try {
      const res = await skuRecycle({
        skuIds: records,
      });
      ElMessage.success(res.message);
      queryForm();
    } catch (e) {
      throw Error(e);
    }
  });
};

const queryList = async () => {
  getClearrulesList({
    status: 0,
  }).then((res) => {
    clearList.value = res.data;
  });
};

onMounted(() => {
  queryList();
});

const toggle = (val, width) => {
  isShowLeft.value = val;
  if (val) {
    containerWidth.value = width;
  }
};
</script>
<style scoped lang="scss">
.mr5 {
  margin-right: 5px;
}

.toolbar_btns {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left {
  padding: 8px;
  margin-bottom: 55px;
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  background-color: transparent;

  .lable {
    color: #3487ff !important;
  }
}

.selectClass {
  &:deep(.el-select__wrapper) {
    background-color: var(--base-small-bg-color) !important;
  }
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}
</style>
<style lang="scss">
.status {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #3a4259;
}

.enable {
  color: #3e66ee;
  width: 18px;
  height: 18px;
  margin-right: 2px;
}

.disabled {
  color: #fc6271;
  width: 18px;
  height: 18px;
  margin-right: 2px;
}
</style>
